require 'fileutils'

class SparseGen
  def self.sparse_gen_percent(filename, percent = 50,
                              num_blocks = 1024 * 1024, block_size = 1024)
    file = File.open(filename, 'wb')
    sparse_block = "\0" * block_size
    rand_string = rand(36**(block_size * 2)).to_s(36)
    puts rand_string
    (num_blocks * percent / 100).times do
      if percent <= 50 
        file.write(sparse_block)
        ((100 - percent) / percent).times do
          start = rand(0..block_size)
          file.write(rand_string[start..start+block_size-1])
        end
      else
        start = rand(0..block_size)
        file.write(rand_string[start..start+block_size-1])
        ((100 - percent) / percent).times do
          file.write(sparse_block)
        end
      end
    end
    file.close
  end

  def self.sparse_dir(dirname, num_files = 1000,
                      percent = 50, num_blocks = 1024, block_size = 1024)
    FileUtils.mkdir_p dirname
    num_files.times do |file|
      sparse_gen_percent(File.join(dirname, "file_#{file}"),
                         percent, num_blocks, block_size)
    end
  end
end

SparseGen.sparse_gen_percent('file')
